var common = require("../../../common/common.js").common;

var shoppingCar = require("../../../common/shoppingCar.js");

var util = require("../../../utils/util.js");

var leader = require("../../../common/leader.js").leader;

var {$author: $author} = require("../../../components/base/authorization.js");

var app = getApp();

// const urls = [
// 'http://v27-dy.ixigua.com/846356c74e8a931001f83813d4af0916/5e7c8f57/video/tos/cn/tos-cn-ve-15/12c65ce3aa204304b23e3731a95e5522/?a=1128&amp;br=0&amp;bt=1284&amp;cr=0&amp;cs=0&amp;dr=0&amp;ds=3&amp;er=&amp;l=202003261817370100140470921B055239&amp;lr=aweme&amp;qs=0&amp,rc=MzZodGs1OTU5czMzaGkzM0ApaDtoN2RkNmQzNzw8NjM7ZWdqNjBzbmdvYjZfLS0vLS9zczFeYTRgNF4vNjUyMl8tMTE6Yw%3D%3D&amp;vl=&amp;vr=',
//   'http://1252076676.vod2.myqcloud.com/d7eee309vodgzp1252076676/302875785285890794073167099/HhGL7OJObiYA.mp4',
//   'http://1252076676.vod2.myqcloud.com/d7eee309vodgzp1252076676/30287db75285890794073167278/WVQpwkgnb9EA.mp4',
//   'http://1252076676.vod2.myqcloud.com/d7eee309vodgzp1252076676/320e66af5285890794073202694/8ksYlGUevogA.mp4',
//   'http://1252076676.vod2.myqcloud.com/d7eee309vodgzp1252076676/30010ead5285890794073141537/DGAx2EgLMEYA.mp4',
//   'http://1252076676.vod2.myqcloud.com/d7eee309vodgzp1252076676/320ed9255285890794073203062/JyqT3zzDH4MA.mp4',
//   'http://1252076676.vod2.myqcloud.com/d7eee309vodgzp1252076676/320ee16a5285890794073203247/okwtzftAVuwA.mp4',
//   'http://1252076676.vod2.myqcloud.com/d7eee309vodgzp1252076676/2fcc59275285890794073114126/ySa5LZ3k4EcA.mp4'
// ]
// const videoList = urls.map((url, index) => ({ id: index + 1, url }))
Page({
    data: {
        pagesLength: 1,
        videoList: [],
        agesLength: 1,
        //仅有一页，不显示返回按钮
        buy_count: 1,
        alert1: 0,
        autoplay: false,
        relatedGoodsNum: 3,
        currentSwiper: 0,
        animationData: "",
        startclientY: "",
        isShow: true,
        //底部遮罩
        goods: [],
        ifStop: true,
        //阻止多次同方向滑动，多次动画效果
        rule: [],
        ruleModal: false,
        tmplIds: [],
        //模板消息tmplIds
        subscribeMessage: true,
        detail: {},
        //当前
        introductionMore: false,
        animationData: {},
        //内容动画
        animationMask: {},
        //蒙板动画
        videoAlert: false,
        video_shopping_set: {},
        showProgress: false,
        play: "play"
    },
    onPlay(e) {},
    onPause(e) {
        //  console.log('pause', e.detail.activeId)
    },
    onEnded(e) {},
    onError(e) {},
    onWaiting(e) {},
    onTimeUpdate(e) {},
    onProgress(e) {},
    onLoadedMetaData(e) {
        console.log("LoadedMetaData", e);
    },
    onLoad: function(options) {
        let that = this;
        let pagesLength = getCurrentPages().length;
        var isIPX = app.globalData.isIPX;
        that.setData({
            isIPX: isIPX,
            pagesLength: pagesLength,
            domain: app.globalData.domain.slice(0, -10)
        });
        if (options.id) {
            that.setData({
                id: options.id
            });
        }
        that.getRule();
        //规则
                that.getGrassList();
        //获取所有的视频
                that.getPlantgrassSet();
        //开启免支付才能上传
                this.getHeader();
    },
    /**
 * 用户点击右上角分享
 */
    onShareAppMessage: function() {
        let that = this;
        return {
            title: that.data.details.name,
            imageUrl: that.data.details.cover_img,
            path: "/grass/pages/grassVideo/grassVideo?id=" + that.data.id
        };
    },
    onShow: function() {
        let that = this;
        that.getBase();
        common.getCart();
        var newPro = that.changeProInfo(that.data.goods);
        var newShoppingCart = shoppingCar.getInfo();
        that.setData({
            cart_count: newShoppingCart.cart_count,
            goods: newPro
        });
        that.animateTrans = wx.createAnimation({
            duration: 600,
            timingFunction: "ease"
        });
        that.animateFade = wx.createAnimation({
            duration: 600,
            timingFunction: "ease"
        });
        leader.getMyLeaderInfo(wx.getStorageSync("user").openid);
        that.getGrassList();
    },
    //获取去右侧胶囊的信息
    getHeader() {
        let menuRect = wx.getMenuButtonBoundingClientRect();
        this.setData({
            topBarHeight: menuRect.height,
            topBarTop: menuRect.top,
            topBarWidth: menuRect.width
        });
    },
    /**
   * 展开更多
   */
    more: function() {
        let that = this;
        that.setData({
            introductionMore: !that.data.introductionMore
        });
    },
    /**
  * 获取规则
  */
    getRule: function() {
        let that = this;
        common.request({
            endpoint: "Plantgrass/person/award_rule",
            method: "post",
            data: {},
            success: res => {
                that.setData({
                    rule: res.extra
                });
            }
        });
    },
    //种草设置
    getPlantgrassSet: function() {
        let that = this;
        common.request({
            endpoint: "Plantgrass/manage/set",
            method: "post",
            success: res => {
                that.setData({
                    plantgrass: res.data
                });
            }
        });
    },
    /**
   * 获取当前种草
   */
    bindChangeSwiper: function(e) {
        let that = this;
        that.data.videoList.map(x => {
            if (e.detail.activeId == x.id) {
                that.changeProInfo(x.pro_info);
                that.setData({
                    details: x,
                    goods: x.pro_info
                });
            }
        });
    },
    /**
  * 取消或者点赞
  */
    praiseAction: function() {
        let that = this;
        common.getUserInfoNew({
            success() {
                let praise_status = that.data.details.praise_status;
                let doparise = praise_status == 2 ? "praise" : "unpraise";
                //praise取消赞
                                common.request({
                    endpoint: "Plantgrass/manage/praise",
                    method: "post",
                    data: {
                        do: doparise,
                        id: that.data.id,
                        praise: that.data.details.praise
                    },
                    success: res => {
                        let info = "details.praise_status";
                        let praiseInfo = "details.praise";
                        let status;
                        let praiseNum;
                        if (praise_status == 2) {
                            status = 1;
                            praiseNum = ++that.data.details.praise;
                        } else {
                            status = 2;
                            praiseNum = --that.data.details.praise;
                        }
                        that.setData({
                            [info]: status,
                            [praiseInfo]: praiseNum
                        });
                    }
                });
            }
        });
    },
    goToDetail(e) {
        common.getUserInfoNew({
            success() {
                wx.navigateTo({
                    url: e.currentTarget.dataset.url
                });
            }
        });
    },
    // 显示商品
    showModal: function() {
        this.animateTrans.translateY(0).step();
        this.animateFade.opacity(1).step();
        this.setData({
            relatedGoodsModals: true,
            animationData: this.animateTrans.export(),
            //动画实例的export方法导出动画数据传递给组件的animation属性
            animationMask: this.animateFade.export()
        });
    },
    // 隐藏商品
    hideModal: function() {
        let that = this;
        that.animateTrans.translateY(300).step();
        that.animateFade.opacity(0).step();
        that.setData({
            animationData: that.animateTrans.export(),
            animationMask: that.animateFade.export()
        });
        setTimeout(() => {
            that.setData({
                relatedGoodsModals: false
            });
        }, 500);
    },
    /**
  * 上传显示奖励规则
  */
    ruleModalShow: function() {
        let that = this;
        if (that.data.plantgrass.paid_status == 1) {
            common.getUserInfoNew({
                success() {
                    that.setData({
                        ruleModal: true
                    });
                }
            });
        } else {
            wx.showModal({
                title: "提示",
                content: "必须购买商品才能上传种草！",
                showCancel: false
            });
        }
    },
    ruleModalHide: function() {
        let that = this;
        that.setData({
            ruleModal: false
        });
    },
    /**
   * 选择图文视频上传 1 图文 2 视频
   */
    gotoUploadPage: function(e) {
        wx.navigateTo({
            url: "/grass/pages/uploadInfo/uploadInfo?type=" + e.currentTarget.dataset.id
        });
    },
    /**
   * 获取所有的视频
   */
    getGrassList: function() {
        let that = this;
        common.request({
            endpoint: "Plantgrass/list/list",
            method: "post",
            data: {
                type: 2
            },
            success: res => {
                //初始化--待优化 播放第一个
                let videoList = res.rows;
                var itemVideo = videoList[1];
                let checkIndex;
                videoList.map((x, index) => {
                    if (x.id == that.data.id) {
                        checkIndex = index;
                    }
                });
                videoList[1] = videoList[checkIndex];
                //跟第一个换位
                                videoList[checkIndex] = itemVideo;
                var goods = that.changeProInfo(videoList[1].pro_info);
                if (goods.length == 1 && !goods[0].id) {
                    //暂时处理，需要后台无商品赋值为空数组
                    goods = [];
                }
                goods.filter(x => {
                    if (x.is_mem_level == 1) {
                        if (x.is_vip == 1) {
                            x.vip_price = Number(x.vip_price) > Number(x.mem_level_price) ? x.mem_level_price : x.vip_price;
                        } else {
                            x.vip_price = x.mem_level_price;
                        }
                    }
                });
                let count = 0;
                goods.forEach(item => {
                    count += item.cart_num;
                });
                that.setData({
                    videoList: videoList,
                    details: videoList[1],
                    goods: goods,
                    cart_count: count
                });
                console.log(this.data.videoList);
            }
        });
    },
    //全局基础配置信息
    getBase: function(openid) {
        var that = this;
        common.request({
            endpoint: "set/app_base",
            method: "get",
            data: {},
            success: res => {
                that.setData({
                    color_header: res.extra.color_header,
                    color_text: res.extra.color_text,
                    color_main: res.extra.color_main,
                    color_minor: res.extra.color_minor,
                    new_member_audit: res.extra.new_member_audit,
                    userAuditStatus: res.extra.userAuditStatus ? res.extra.userAuditStatus : 2,
                    video_shopping_set: res.extra.video_shopping_set,
                    showProgress: res.extra.video_shopping_set.status == 1
                });
                //处理模块开关
                                var features = common.getModulesSwich(res.extra.features);
                //处理数据格式
                                that.setData({
                    features: features
                });
                if (res.extra.video_shopping_set.status == 1) {
                    setTimeout(() => {
                        that.receive();
                        that.setData({
                            play: "pause"
                        });
                    }, parseInt(that.data.video_shopping_set.second) * 1e3);
                }
            }
        });
    },
    receive: function() {
        var that = this;
        common.request({
            endpoint: "VideoShopping/manage/receive",
            method: "get",
            data: {},
            success: res => {
                if (res.code == 0) {
                    that.setData({
                        videoAlert: true
                    });
                    if (parseInt(that.data.video_shopping_set.limit) == res.extra.received_times) {
                        that.setData({
                            showProgress: false
                        });
                    }
                } else {
                    that.setData({
                        showProgress: false
                    });
                }
            },
            fail: res => {
                that.setData({
                    showProgress: false
                });
            }
        });
    },
    //获取tmplIds
    getTmplIds: function() {
        let that = this;
        common.request({
            endpoint: "set/template_get",
            method: "post",
            data: {},
            header: {
                "content-type": "application/json"
            },
            success: res => {
                console.log(res);
                let tmplIds = [];
                let subscribeMessage = true;
                res.extra.map(v => {
                    if ((v.type == "21" || v.type == "22" || v.type == "23") && v.status == "1") {
                        tmplIds.push(v.template_id);
                    }
                });
                if (!tmplIds.length) {
                    subscribeMessage = false;
                }
                that.setData({
                    tmplIds: tmplIds,
                    subscribeMessage: subscribeMessage
                });
            }
        });
    },
    join_cart: function(e) {
        let that = this;
        var id = e.detail.id;
        that.setData({
            joinCate: 1
        });
        that.join_cart_current(e);
    },
    //加入购物车 此处商品详情接口需要跳转，并且增加加入中的提示
    join_cart_current(e) {
        var that = this;
        var id = e.currentTarget.dataset.id;
        let single = e.currentTarget.dataset.single;
        common.request({
            // endpoint: 'product/product_info',
            endpoint: "product/shopping-push",
            method: "post",
            data: {
                id: id
            },
            success: res => {
                let details = res.extra;
                details.sku_attribute = details.sku_attribute.map(item => {
                    item.attribute_value = this.selectSingleSku(item.attribute_value);
                    return item;
                });
                let sku_attribute = details.sku_attribute;
                let sku = sku_attribute.reduce((s, v) => {
                    s = this.reBlanceSku(s, parseInt(v.attribute_key.id), parseInt(v.attribute_value[0].id));
                    return s;
                }, "");
                let sku_info = this.getProductBySku(details.sku, sku);
                let cart_count = wx.getStorageSync("cart_count");
                if (single == 1) {
                    that.setData({
                        minimum_num: e.currentTarget.dataset.minimumnum,
                        step_num: e.currentTarget.dataset.stepnum
                    });
                    that.join_cart_current_ch(details, e);
                    if (that.data.subscribeMessage) {
                        wx.requestSubscribeMessage({
                            tmplIds: that.data.tmplIds,
                            success(res) {},
                            fail(err) {
                                console.log(err);
                            },
                            complete() {}
                        });
                    }
                } else {
                    that.setData({
                        details: details,
                        sku: sku,
                        alert: 1,
                        product_id: id,
                        sku_info: sku_info,
                        proId: id,
                        buy_count: 1
                    });
                }
            }
        });
    },
    //单规格商品购买
    join_cart_current_ch: function(details, e) {
        var that = this;
        var id = e.currentTarget.dataset.id;
        let single = e.currentTarget.dataset.single;
        details.sku_attribute = details.sku_attribute.map(item => {
            item.attribute_value = this.selectSingleSku(item.attribute_value);
            return item;
        });
        let sku_attribute = details.sku_attribute;
        let sku = sku_attribute.reduce((s, v) => {
            s = this.reBlanceSku(s, parseInt(v.attribute_key.id), parseInt(v.attribute_value[0].id));
            return s;
        }, "");
        let sku_info = this.getProductBySku(details.sku, sku);
        if (sku_info.stock_number >= 1) {
            that.cartRequest(sku_info.item_id, "add", id, 1);
        } else {
            wx.showToast({
                title: "库存不足",
                icon: "none"
            });
        }
    },
    cartRequest(sku, type, id, single) {
        let that = this;
        let num = 0;
        if (single == 1) {
            var addC = that.data.joinCate == 1 ? parseInt(that.data.minimum_num) : parseInt(that.data.step_num);
            num = type == "add" ? addC : -addC;
        } else {
            num = that.data.buy_count;
        }
        let goods = that.data.goods;
        let i = goods.findIndex(item => item.id == id);
        if (type != "add") {
            if (goods[i].cart_num <= parseInt(that.data.minimum_num)) {
                num = -goods[i].cart_num;
            }
        }
        common.request({
            endpoint: "Order/cart/add",
            method: "post",
            data: {
                leader_id: that.data.myleaderinfo.leader_id != -1 ? that.data.myleaderinfo.leader_id : 0,
                sku_id: sku,
                business_id: 0,
                num: num,
                flag: 0,
                type: 0
            },
            success: res => {
                if (single == 1) {
                    if (type == "add") {
                        goods[i].cart_num += num;
                    } else {
                        goods[i].cart_num += num;
                    }
                } else {
                    goods[i].cart_num += that.data.buy_count;
                }
                if (goods[i].cart_num < 0) {
                    goods[i].cart_num = 0;
                }
                let count = 0;
                goods.forEach(item => {
                    count += item.cart_num;
                });
                that.setData({
                    goods: goods,
                    alert: 0,
                    cart_count: count
                });
                if (that.data.subscribeMessage) {
                    wx.requestSubscribeMessage({
                        tmplIds: that.data.tmplIds,
                        success(res) {},
                        fail(err) {
                            console.log(err);
                        },
                        complete() {}
                    });
                }
            },
            fail: err => {
                wx.showModal({
                    title: "提示",
                    content: err.message
                });
            }
        });
    },
    /** 
   * 添加 sku 属性
   */
    addSkuAttribute: function(e) {
        let key_id = parseInt(e.currentTarget.dataset.key_id);
        let value_id = parseInt(e.currentTarget.dataset.value_id);
        let a_key_index = parseInt(e.currentTarget.dataset.a_key_index);
        let a_value_index = parseInt(e.currentTarget.dataset.a_value_index);
        let sku = this.data.sku;
        sku = this.reBlanceSku(sku, key_id, value_id);
        let attribute = this.data.details.sku_attribute;
        attribute = this.selectSku(attribute, a_key_index, a_value_index);
        let sku_info = this.getProductBySku(this.data.details.sku, sku);
        this.setData({
            sku: sku,
            ["details.sku_attribute"]: attribute,
            sku_info: sku_info
        });
    },
    /** 
   * 重平衡 sku
   * key_id: integer
   */
    reBlanceSku: function(sku, key_id, value_id) {
        let sku_lib = sku != "" ? this.splitSku(sku) : [];
        sku_lib = this.addSku(sku_lib, {
            key_id: key_id,
            value_id: value_id
        });
        sku_lib = this.sortSku(sku_lib);
        return this.buildSku(sku_lib);
    },
    /** 
   * 重建 sku
   */
    buildSku: function(sku_lib) {
        return sku_lib.map(item => {
            return item.key_id + "," + item.value_id;
        }).join("|");
    },
    /** 
   * 对选择的 sku 属性进行排序
   */
    sortSku: function(sku_lib) {
        return sku_lib.sort((pre, next) => {
            if (pre.key_id > next.key_id) {
                return 1;
            } else if (pre.key_id < next.key_id) {
                return -1;
            } else {
                return 0;
            }
        });
    },
    /** 
   * 分割现有 sku 成对象数组
   */
    splitSku: function(sku) {
        return sku.split("|").map(sku_tmp => {
            let [key, value] = sku_tmp.split(",");
            const t = {};
            t.key_id = parseInt(key);
            t.value_id = parseInt(value);
            return t;
        });
    },
    /** 
   * 添加一个 sku
   */
    addSku: function(sku_lib, sku) {
        let t = sku_lib.filter(item => {
            if (item.key_id === sku.key_id) {
                return false;
            }
            return true;
        });
        t.push(sku);
        return t;
    },
    /** 
   * 选择 sku
   */
    selectSku: function(attribues, a_index, v_index = 0) {
        if (attribues[a_index]) {
            let values = attribues[a_index].attribute_value;
            values = values.map(item => {
                item.selected = false;
                return item;
            });
            values[v_index].selected = true;
            attribues[a_index].attribute_value = values;
        }
        return attribues;
    },
    /** 
   * 选择单个 sku 属性
   */
    selectSingleSku: function(attribute_value, v_index = 0) {
        attribute_value.map(item => {
            item.selected = false;
            return item;
        });
        attribute_value[v_index].selected = true;
        return attribute_value;
    },
    //加入成功后，更新购物车数量
    save_count: function(e) {
        var that = this;
        //判断是否是新人商品
                if (that.data.addShoppingCar) {
            //非新人商品
            this.setData({
                buy_count: parseInt(e.detail.value)
            });
        } else {
            if (that.data.newUserBuyLimit != 0) {
                if (parseInt(e.detail.value > that.data.newUserBuyLimit)) {
                    //判断数值大小有没有超过购买上限
                    //超过上限，设置为上限值
                    that.setData({
                        buy_count: that.data.newUserBuyLimit
                    });
                } else {
                    that.setData({
                        buy_count: parseInt(e.detail.value)
                    });
                }
            } else {
                that.setData({
                    buy_count: parseInt(e.detail.value)
                });
            }
        }
    },
    blur: function(e) {
        let count = e.detail.value;
        if (count <= 0) {
            count = 1;
        }
        this.setData({
            buy_count: parseInt(count)
        });
    },
    reduce_count: function() {
        let buy_count = this.data.buy_count;
        if (buy_count > 1) {
            buy_count--;
        }
        this.setData({
            buy_count: buy_count
        });
    },
    add_count: function(e) {
        let that = this;
        that.add_count_ch(e);
        if (that.data.subscribeMessage) {
            wx.requestSubscribeMessage({
                tmplIds: that.data.tmplIds,
                success(res) {},
                fail(err) {
                    console.log(err);
                },
                complete() {}
            });
        }
    },
    add_count_ch: function(e) {
        let that = this;
        let restrictions = that.data.addShoppingCar ? e.currentTarget.dataset.restrictions : e.currentTarget.dataset.newlimit;
        let buy_count = this.data.buy_count;
        console.log(restrictions + "," + buy_count);
        if (restrictions == 0) {
            buy_count++;
        } else {
            if (buy_count >= restrictions) {
                wx.showModal({
                    title: "提示",
                    content: "本商品限购" + restrictions + "份"
                });
                buy_count = restrictions;
            } else {
                buy_count++;
            }
        }
        this.setData({
            buy_count: buy_count
        });
    },
    loginSuccess(e) {
        var user = e.detail.user;
        var info = this.data.info;
        info.img = user.avatar;
        info.nickname = user.nickname;
        this.setData({
            info: info
        });
    },
    /**
   * 根据 sku 获取物品
   */
    getProductBySku: function(sku_products, sku) {
        return sku_products[sku];
    },
    buy: function(e) {
        var that = this;
        var alert = that.data.alert;
        var details = that.data.details;
        var sku_info = that.data.sku_info;
        var buy_count = that.data.buy_count;
        var id = that.data.goodsId;
        var sku_id = sku_info.item_id;
        let sku_item = sku_info.item_id + "," + buy_count + "," + sku_info.credit_sent + "," + details.only_express;
        var price = "";
        if (e.currentTarget.dataset.price) {
            price = e.currentTarget.dataset.price;
        }
        if (sku_info.stock_number >= buy_count) {
            wx.navigateTo({
                url: "/newPlace_order/pages/newPlace_order/newPlace_order?sku_item=" + sku_item + "&status=" + 0 + "&newuserprice=" + price
            });
            that.setData({
                alert: 0,
                addShoppingCar: true,
                newUserProductPrice: ""
            });
        } else {
            wx.showToast({
                title: "库存不足",
                icon: "none"
            });
            that.setData({
                alert: 0
            });
        }
    },
    join_goods: function() {
        let that = this;
        that.cartRequest(that.data.sku_info.item_id, "add", that.data.details.product_id, 2);
        // that.join_goods_ch();
        // if (that.data.subscribeMessage) {
        //   wx.requestSubscribeMessage({
        //     tmplIds: that.data.tmplIds,
        //     success(res) {
        //     },
        //     fail(err) {
        //       console.log(err);
        //     },
        //     complete() {
        //     }
        //   })
        // }
        },
    join_goods_ch: function() {
        var that = this;
        var alert = that.data.alert;
        var cart_count = wx.getStorageSync("cart_count") || 0;
        var details = that.data.details;
        var sku_info = that.data.sku_info;
        var buy_count = that.data.buy_count;
        var id = that.data.product_id;
        cart_count = cart_count + buy_count;
        var cart = wx.getStorageSync("cart") || [];
        if (cart_count <= 99999) {
            if (sku_info.stock_number >= buy_count) {
                if (cart == "") {
                    let goods = {
                        id: sku_info.item_id,
                        product_id: id,
                        img: details.icon_img,
                        title: details.name,
                        varieties: sku_info.title,
                        price: sku_info.price,
                        o_price: sku_info.o_price,
                        count: buy_count,
                        stock_number: sku_info.stock_number,
                        select: 1,
                        proID: id,
                        status: 1,
                        credit_sent: sku_info.credit_sent || 0,
                        spec_fund: details.spec_fund,
                        is_vip: details.is_vip,
                        is_mem_level: sku_info.is_mem_level,
                        vip_price: Number(sku_info.vip_price) > Number(sku_info.mem_level_price) ? sku_info.mem_level_price : sku_info.vip_price
                    };
                    wx.showToast({
                        title: "加入购物车成功",
                        icon: "none",
                        success: res => {
                            wx.setStorage({
                                key: "cart_count",
                                data: cart_count
                            });
                            this.setData({
                                cart_count: cart_count
                            });
                            common.changeIconNum(cart_count, 2);
                            var cart = wx.getStorageSync("cart") || that.data.cart;
                            if (!cart) {
                                cart = [];
                            }
                            cart.push(goods);
                            wx.setStorage({
                                key: "cart",
                                data: cart
                            });
                            setTimeout(() => {
                                let newShoppingCart = shoppingCar.getInfo();
                                var newPro = that.changeProInfo(that.data.goods, newShoppingCart);
                                that.setData({
                                    buy_count: 1,
                                    alert: 0,
                                    goods: newPro
                                });
                            }, 500);
                        }
                    });
                } else {
                    var total = 0;
                    var index = 0;
                    for (var i = 0; i < cart.length; i++) {
                        if (sku_info.item_id != cart[i]["id"]) {
                            total++;
                        } else {
                            index = i;
                            break;
                        }
                    }
                    if (total == cart.length) {
                        let goods = {
                            id: sku_info.item_id,
                            product_id: id,
                            img: details.icon_img,
                            title: details.name,
                            varieties: sku_info.title,
                            price: sku_info.price,
                            o_price: sku_info.o_price,
                            count: buy_count,
                            stock_number: sku_info.stock_number,
                            select: 1,
                            proID: id,
                            status: 1,
                            credit_sent: sku_info.credit_sent || 0,
                            spec_fund: details.spec_fund,
                            is_vip: details.is_vip,
                            is_mem_level: sku_info.is_mem_level,
                            vip_price: Number(sku_info.vip_price) > Number(sku_info.mem_level_price) ? sku_info.mem_level_price : sku_info.vip_price
                        };
                        wx.showToast({
                            title: "加入购物车成功",
                            icon: "none",
                            success: res => {
                                wx.setStorage({
                                    key: "cart_count",
                                    data: cart_count
                                });
                                this.setData({
                                    cart_count: cart_count
                                });
                                common.changeIconNum(cart_count, 2);
                                var cart = wx.getStorageSync("cart") || that.data.cart;
                                cart.push(goods);
                                wx.setStorage({
                                    key: "cart",
                                    data: cart
                                });
                                setTimeout(() => {
                                    let newShoppingCart = shoppingCar.getInfo();
                                    var newPro = that.changeProInfo(that.data.goods, newShoppingCart);
                                    that.setData({
                                        buy_count: 1,
                                        alert: 0,
                                        goods: newPro
                                    });
                                }, 500);
                            }
                        });
                    } else {
                        cart[index]["count"] = cart[index]["count"] + buy_count;
                        wx.showToast({
                            title: "加入购物车成功",
                            icon: "none",
                            success: res => {
                                wx.setStorage({
                                    key: "cart_count",
                                    data: cart_count
                                });
                                this.setData({
                                    cart_count: cart_count
                                });
                                common.changeIconNum(cart_count, 2);
                                wx.setStorage({
                                    key: "cart",
                                    data: cart
                                });
                                setTimeout(() => {
                                    let newShoppingCart = shoppingCar.getInfo();
                                    var newPro = that.changeProInfo(that.data.goods, newShoppingCart);
                                    that.setData({
                                        buy_count: 1,
                                        alert: 0,
                                        goods: newPro
                                    });
                                }, 500);
                            }
                        });
                    }
                }
            } else {
                wx.showToast({
                    title: "加入购物车失败",
                    icon: "none"
                });
            }
        } else {
            wx.showToast({
                title: "购物车最多加99999个商品！",
                icon: "none"
            });
        }
    },
    //提示框
    toastControl(content, time) {
        var that = this;
        that.setData({
            toastContent: content,
            toastHide: false
        });
        //显示提示框
                setTimeout(() => {
            that.setData({
                toastHide: true
            });
        }, !time ? 3e3 : time);
        //定时隐藏提示框,默认3秒后隐藏
        },
    //购物车减
    reduceCount(e) {
        let that = this;
        that.setData({
            joinCate: 2
        });
        that.setData({
            minimum_num: e.currentTarget.dataset.minimumnum,
            step_num: e.currentTarget.dataset.stepnum
        });
        if (e.currentTarget.dataset.single == 1) {
            var params = {
                id: e.currentTarget.dataset.id
            };
            common.request({
                // endpoint: 'product/product_info',
                endpoint: "product/shopping-push",
                method: "post",
                data: params,
                success: res => {
                    let details = res.extra;
                    this.setData({
                        commission_show: details.commission_show
                    });
                    details.sku_attribute = details.sku_attribute.map(item => {
                        item.attribute_value = this.selectSingleSku(item.attribute_value);
                        return item;
                    });
                    let sku_attribute = details.sku_attribute;
                    let sku = sku_attribute.reduce((s, v) => {
                        s = this.reBlanceSku(s, parseInt(v.attribute_key.id), parseInt(v.attribute_value[0].id));
                        return s;
                    }, "");
                    let sku_info = this.getProductBySku(details.sku, sku);
                    that.cartRequest(sku_info.item_id, "reduce", e.currentTarget.dataset.id, 1);
                }
            });
        } else {
            wx.showToast({
                title: "该商品是多属性商品，请到购物车操作",
                icon: "none"
            });
        }
    },
    //加
    addCount(e) {
        let that = this;
        that.setData({
            joinCate: 2
        });
        that.addCount_ch(e);
        // if (that.data.subscribeMessage) {
        //   wx.requestSubscribeMessage({
        //     tmplIds: that.data.tmplIds,
        //     success(res) {
        //     },
        //     fail(err) {
        //       console.log(err);
        //     },
        //     complete() {
        //     }
        //   })
        // }
        },
    addCount_ch: function(e) {
        this.join_cart_current(e);
    },
    /**
   * 商品信息修改
   */
    changeProInfo(proInfo, cartInfoParamter) {
        // console.log("商品修改")
        // console.log(proInfo)
        // console.log(proInfo)
        var cartInfo = cartInfoParamter ? cartInfoParamter.statisticsArry : shoppingCar.getInfo().statisticsArry;
        if (proInfo.length > 0) {
            proInfo.forEach((item, index) => {
                if (cartInfo.length > 0) {
                    for (var i = 0; i < cartInfo.length; i++) {
                        if (item.id == cartInfo[i].product_id) {
                            item.buyCount = cartInfo[i].count;
                            break;
                        } else {
                            item.buyCount = 0;
                        }
                    }
                } else {
                    item.buyCount = 0;
                }
            });
        }
        return proInfo;
    },
    //关闭蒙层
    close_alert: function(e) {
        this.setData({
            alert: 0
        });
    },
    close: function() {
        var that = this;
        that.setData({
            videoAlert: false,
            play: "play"
        });
        setTimeout(() => {
            that.receive();
            that.setData({
                play: "pause"
            });
        }, parseInt(that.data.video_shopping_set.second) * 1e3);
    }
});